package com.cheng.example.book.advise151.chap2;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;

/**
 * 建议22：用整数类型处理货币
 *
 * 1、NumberFormat类使用
 * 2、使用BigDecimal和使用整型
 *
 */
public class Client22 {
    public static void main(String[] args) {
        currencyFormat();
    }

    private static void currencyFormat() {
        //按系统预设的货币格式输出，这里是人民币
        NumberFormat nf = NumberFormat.getCurrencyInstance();
        System.out.println(nf.format(123.456));//￥123.46
        //按指定的货币格式输出，这里是美元
        //Locale locale = Locale.US;
        nf = NumberFormat.getCurrencyInstance(Locale.US);
        System.out.println(nf.format(123.456));//$123.46
    }

    private static void numberFormat() {
        double d = 12345.676688000;
        NumberFormat nf = NumberFormat.getNumberInstance();
        System.out.println(nf.format(d));//12,345.677 默认只保留到小数点后三位
        nf.setMinimumIntegerDigits(2);
        System.out.println(nf.format(d));//12,345.677 整数部分大于2位按默认最大小数位数3位输出
        d = 1234.0;
        nf.setMaximumIntegerDigits(3);
        System.out.println(nf.format(d));//234
        nf = NumberFormat.getInstance();
        d = 12345.6766;
        nf.setMinimumFractionDigits(1);
        System.out.println(nf.format(d));//12,345.677 小数部分大于1位，按默认最大小数位数3位输出
        nf.setMinimumFractionDigits(5);
        System.out.println(nf.format(d));//12,345.67660 不够位数补0
        nf.setMaximumFractionDigits(1);
        System.out.println(nf.format(d));//12,345.7
        nf = NumberFormat.getNumberInstance(Locale.US);
        d = 12345.6789;
        System.out.println(nf.format(d));//12,345.679
        nf = NumberFormat.getNumberInstance(Locale.FRANCE);
        System.out.println(nf.format(d));//12 345,679
    }


    private static void decimalFormat() {
        double d1 = 123456.36987, d2 = 12.3698;
        DecimalFormat nf = new DecimalFormat("0000.000");
        System.out.println("d1=" + nf.format(d1) + " d2=" + nf.format(d2));//d1=123456.370 d2=0012.370
        nf = new DecimalFormat("#");
        System.out.println("d1=" + nf.format(d1));//d1=123456
        nf = new DecimalFormat(".####");
        System.out.println("d1=" + nf.format(d1));//d1=123456.3699
        nf = new DecimalFormat("0000,0000.00000");//注意“,”不能放在小数部分
        System.out.println("d1=" + nf.format(d1));//d1=0012,3456.36987
    }



}